﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Snowdreamist.Runtime;
using Snowdreamist.Runtime.Services;

namespace Snowdreamist.IO
{
    public class TemporaryFileRepository : ITemporaryFileRepository, IModuleRuntimeServiceGenerator, IModuleRuntimeService
    {
        public virtual void Initialize() { }

        public string NewTempFile()
        {
            lock (this)
            {
                var filename = Path.GetTempFileName();
                this._fileList.Add(filename);
                return filename;
            }
        }

        public void Clear()
        {
            lock (this)
            {
                foreach (var filename in this._fileList)
                    if (File.Exists(filename))
                        File.Delete(filename);
            }
        }

        public IModuleRuntimeService GetModuleRuntimeService(IModuleDefinition definition, out Type serviceConrtactType)
        {
            serviceConrtactType = typeof(ITemporaryFileRepository);

            return new TemporaryFileRepository();
        }

        public virtual void OnRuntimeDisposing()
        {
            if (SystemRuntime.Current.Configuration.TempFile.AutoClean)
                this.Clear();
        }

        public void Initialize(ModuleRuntime runtime)
        {
            // module, nothing
        }

        public void Destroy(ModuleRuntime runtime)
        {
            // module, clear
            if (SystemRuntime.Current.Configuration.TempFile.AutoClean)
                this.Clear();
        }

        #region private

        private readonly List<string> _fileList = new List<string>();

        #endregion private
    }
}